package org.az.netty_study.p14_netty综合案例2_聊天室.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.az.netty_study.p14_netty综合案例2_聊天室.message.LoginRequestMessage;
import org.az.netty_study.p14_netty综合案例2_聊天室.message.LoginResponseMessage;
import org.az.netty_study.p14_netty综合案例2_聊天室.server.service.UserServiceFactory;
import org.az.netty_study.p14_netty综合案例2_聊天室.server.session.SessionFactory;

/**
 * 该handler只关心LoginRequestMessage类型的消息
 */
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        boolean login = UserServiceFactory.getUserService().login(msg.getUsername(), msg.getPassword());
        LoginResponseMessage responseMessage;
        if (login) {
            SessionFactory.getSession().bind(ctx.channel(), msg.getUsername());
            responseMessage = new LoginResponseMessage(true, "登录成功");
        } else {
            responseMessage = new LoginResponseMessage(false, "登录失败，用户名或密码错误");
        }
        ctx.writeAndFlush(responseMessage);
    }
}
